package spider

import (
	"fmt"
	"math/rand"
	"strconv"
	"study/dao"
	"study/model"
	"study/util"
	"time"

	"github.com/gocolly/colly"
)

func SouGouHaHaSpider() {
	c := NewCollector()

	url := "http://haha.sogou.com/tag/li/搞笑漫画/new/"
	for i := 1; i < 144; i++ {

		c.OnHTML("div[id='ind-list']", func(h *colly.HTMLElement) {
			h.ForEach("div[class='hc-c']", func(i int, h *colly.HTMLElement) {
				fmt.Println("================================================")
				imgUrl := h.ChildAttr(".img_cont", "img_url")
				imgUrl = "http:" + imgUrl
				// fmt.Println(imgUrl)
				title := h.ChildText(".hcc-pic .tx")
				// fmt.Println(title)
				joke := model.Joke{}
				dao.Db.Where("title = ? and create_time > ?", title, "2021-08-25 00:00:00").First(&joke)
				if joke.Id == 0 {
					// joke := model.Joke{}
					joke.Src = imgUrl
					joke.Title = title
					now := time.Now()
					// now := time.Now().Format("2006-01-02 15:04:05")

					joke.SourceId = 652
					joke.Good = int(util.RandInt64(int64(1000), int64(5000)))
					joke.Bad = rand.Intn(500)
					joke.CreateTime = util.GetFormatTime(now)
					joke.UpdateTime = util.GetFormatTime(now)
					joke.Type = 1

					img, err := util.GetImgInfo(imgUrl)
					if err == nil {
						joke.Height = img.Bounds().Dy()
						joke.Width = img.Bounds().Dx()
						imgName, _, _ := util.DownImg(imgUrl, imgPath)
						joke.Img = "20210818/" + imgName
						fmt.Println(joke)
						dao.Db.Create(&joke)
					}

				}
			})
		})
		c.Visit(url + strconv.Itoa(i))
		// c.Wait()
	}

}
